package me.zhenqu.redis.utils;

import java.io.ByteArrayOutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: yibing.tan
 * Date: 11-11-14
 * Time: 下午4:29
 * To change this template use File | Settings | File Templates.
 */
public class ArrayCoder extends CacheCoder<Object[]> {
    private CacheCoder innerCoder;

    public ArrayCoder(CacheCoder innerCoder) {
        this.innerCoder = innerCoder;
    }

    @Override
    public byte[] encode(Object[] arr) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        writeBytes(bos, ByteUtil.parseInt(arr.length, 4));

        for (Object o1 : arr) {
            byte[] encode = innerCoder.encode(o1);
            writeBytes(bos, ByteUtil.parseInt(encode.length, 4));
            writeBytes(bos, encode);
        }
        return bos.toByteArray();
    }


    @Override
    public Object[] decode(byte[] val, int offset, int size) {
        int len = ByteUtil.toInt(val, offset, 4);
        Object[] arr = new Object[len];
        offset += 4;
        for (int i = 0; i < len; i++) {
            int l = ByteUtil.toInt(val, offset, 4);
            offset += 4;
            arr[i] = innerCoder.decode(val, offset, l);
            offset += l;
        }

        return arr;
    }

    public static void main(String[] args) {
        String[] test = {"1", "2", "3", "4"};
        ArrayCoder coder = new ArrayCoder(StringCoder.INST);
        byte[] encode = coder.encode(test);
        Object[] decode = coder.decode(encode);
        for (Object o : decode) {
            System.out.println("o = " + o);
        }
    }
}
